package com.pug.service.user;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pug.pojo.LoginUser;
import com.pug.service.jwt.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public LoginUser login(String username, String password) throws JsonProcessingException {
        // 用户验证
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            e.printStackTrace();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        loginUser.setIpaddr("127.0.0.1");
        loginUser.setLoginTime(new Date().getTime());
        loginUser.setExpireTime(new Date().getTime() + JwtTokenUtils.REDIS_TOKEN_EXPIRATION);
        String token = JwtTokenUtils.createToken(loginUser);
        loginUser.setToken(token);
        // 设置缓存的数据
        redisTemplate.opsForValue().set("sys:token:string:" + token, token, JwtTokenUtils.REDIS_TOKEN_EXPIRATION, TimeUnit.MILLISECONDS);
        // 生成token
        return loginUser;
    }

}
